package com.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.apiresult.CommonResult;
import com.common.apiresult.ResultCode;
import com.common.domain.dto.AddGuestRecordDTO;
import com.common.domain.dto.GuestRecordQueryDTO;
import com.common.domain.vo.GuestPageVO;
import com.common.domain.vo.GuestVO;
import com.common.utils.TimeUtil;
import com.service.serviceInterface.GuestService;
import com.service.serviceInterface.UserService;
import com.system.entity.Guest;
import com.system.mapper.GuestMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 *
 */
@Service
public class GuestServiceImpl extends ServiceImpl<GuestMapper, Guest>
        implements GuestService {
    @Resource
    private GuestService guestService;
    @Resource
    private GuestMapper guestMapper;
    @Resource
    private UserService userService;
    @Resource
    private TimeUtil timeUtil;

    @Override
    public CommonResult getData(GuestRecordQueryDTO dto, long userId) {
        IPage<Guest> page = select(dto, userId);
        List<Guest> list = page.getRecords();
        if (list.size() <= 0) {
            return CommonResult.failed(ResultCode.RETURNNULL);
        }
        List<GuestVO> vos = new ArrayList<>();
        for (Guest i : list) {
            GuestVO guestVO = new GuestVO();
            BeanUtils.copyProperties(i, guestVO);
            if (!Objects.isNull(i.getModifyUserId())) {
                guestVO.setModifyUserName(userService.getUserNameById(i.getModifyUserId()));
            }
            if (timeUtil.comparableNowTime(i.getEnterTime()) < 0) {
                guestVO.setDeleteUpdate(false);
            } else {
                guestVO.setDeleteUpdate(true);
            }
            vos.add(guestVO);
        }
        GuestPageVO pageVO = new GuestPageVO();
        pageVO.setVo(vos).setTotal(page.getTotal());
        return CommonResult.success(pageVO);
    }

    @Override
    public CommonResult delete(String id) {
        if (id.contains(",")) {
            String[] strings = id.split(",");
            List<String> collect = Arrays.stream(strings).filter(i -> timeUtil.comparableNowTime(guestService.getById(i).getEnterTime()) > 0).collect(Collectors.toList());
            if (collect.size() <= 0) {
                return CommonResult.failed(ResultCode.DELETEEXCEPTION, "不能删除过去的记录");
            }
            return guestService.removeByIds(collect) ? CommonResult.success() : CommonResult.failed();
        }
        if (timeUtil.comparableNowTime(guestService.getById(id).getEnterTime()) < 0) {
            return CommonResult.failed(ResultCode.DELETEEXCEPTION, "不能删除过去的记录");
        }
        return guestService.removeById(id) ? CommonResult.success() : CommonResult.failed();
    }

    @Override
    public CommonResult add(AddGuestRecordDTO dto, long userId) {
        Guest guest = new Guest();
        if (dto.getEnterTime().indexOf(".") != -1) {
            dto.setEnterTime(dto.getEnterTime().substring(0, dto.getEnterTime().indexOf(".")));
        }
        guest.setName(dto.getName()).setPhone(dto.getPhone()).setIdentity(dto.getIdentity()).setSeason(dto.getSeason()).setEnterTime(LocalDateTime.parse(dto.getEnterTime())).setAddUserId(userId).setAddTime(LocalDateTime.now());
        return guestService.insert(guest) ? CommonResult.success() : CommonResult.failed();
    }

    @Override
    public CommonResult updateData(AddGuestRecordDTO dto, long userId) {
        if (Objects.isNull(dto.getId()) || StringUtils.isBlank(String.valueOf(dto.getId()))) {
            return CommonResult.failed(ResultCode.VALIDATE_FAILED);
        }
        Guest guest = new Guest();
        guest.setId(dto.getId()).setName(dto.getName()).setIdentity(dto.getIdentity()).setPhone(dto.getPhone())
                .setModifyUserId(userId).setModifyTime(LocalDateTime.now());
        if (StringUtils.isNotBlank(dto.getSeason())) {
            guest.setSeason(dto.getSeason());
        }
        try {
            guest.setEnterTime(LocalDateTime.parse(dto.getEnterTime(), DateTimeFormatter.ISO_DATE_TIME));
        } catch (Exception e) {
            guest.setEnterTime(LocalDateTime.parse(dto.getEnterTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        }
        return guestService.updateById(guest) ? CommonResult.success() : CommonResult.failed();
    }


    @Override
    public IPage<Guest> select(GuestRecordQueryDTO dto, long userId) {
        IPage<Guest> guestIPage = selectList(dto, userId);
        return guestIPage;
    }

    @Override
    @Transactional(rollbackFor = SQLException.class)
    public boolean insert(Guest guest) {
        return guestMapper.insert(guest) == 1;
    }

    public IPage<Guest> selectList(GuestRecordQueryDTO dto, long userId) {
        String date1 = "";
        String date2 = "";
        if (dto.getDateRange() != null && dto.getDateRange().get(0) != null && dto.getDateRange().get(0) != "") {
            date1 = dto.getDateRange().get(0);
        }
        if (dto.getDateRange() != null && dto.getDateRange().get(1) != null && dto.getDateRange().get(1) != "") {
            date2 = dto.getDateRange().get(1);
        }
        log.error(dto.getPageNum() + " " + dto.getPageSize() + " " + userId);
        Page<Guest> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        return guestService.page(page, addCondition(dto, date1, date2, userId));
    }

    public LambdaQueryWrapper<Guest> addCondition(GuestRecordQueryDTO dto, String date1, String date2, long userId) {
        LambdaQueryWrapper<Guest> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(dto.getName())) {
            wrapper.like(Guest::getName, dto.getName());
        }
        if (StringUtils.isNotBlank(dto.getPhone())) {
            wrapper.like(Guest::getPhone, dto.getPhone());
        }
        if (StringUtils.isNotBlank(dto.getRole())) {
            wrapper.like(Guest::getIdentity, dto.getRole());
        }
        if (StringUtils.isNotBlank(dto.getEnterTime())) {
            wrapper.eq(Guest::getEnterTime, dto.getEnterTime());
        }
        if (StringUtils.isNotBlank(date1) && StringUtils.isNotBlank(date2)) {
            wrapper.between(Guest::getEnterTime, date1, date2);
        }
        if (!Objects.isNull(userId)) {
            wrapper.eq(Guest::getAddUserId, userId);
        }
        return wrapper;
    }
}




